package com.cross.mutil;

import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.dom4j.DocumentException;

import com.cross.core.AbstractReader;
import com.cross.core.Header;
import com.cross.core.Reader;
import com.cross.core.Row;
import com.cross.exception.CrossException;
import com.cross.jdbc.SimpleJdbcReader;

/**
 * 复合SQL读入器:将多个SimpleJdbcReader读取器合并为一个。
 * 依次从多个读取器中读取数据
 * 
 * 2009-3-26
 * 
 * @author craziness_stone
 */
public class SimpleSQLListReader extends AbstractReader {

	private Reader<Row>[] readers;

	private int index = 0;

	private Reader<Row> currentReader = null;

	public SimpleSQLListReader(List<String> sqlList, Connection con)
			throws CrossException, FileNotFoundException, DocumentException, SQLException {
		header = new Header();
		readers = new Reader[sqlList.size()];
		for(int i=0; i< sqlList.size(); i++){
			Reader reader = new SimpleJdbcReader(sqlList.get(i), con);
			readers[i] = reader;
		}
	}
	
	@Override
	protected boolean nextRow() {
		return nextRowImpl();
	}

	private boolean nextRowImpl() {
		if (currentReader != null && currentReader.hasNext()) {
			currentRow = currentReader.next();
			return true;
		}
		currentReader = nextReader();
		if (currentReader == null) {
			return false;
		}
		return nextRowImpl();
	}

	private Reader nextReader() {
		Reader reader = null;
		while(index < readers.length && (reader = readers[index++]) == null){
		}
		if(reader == null){
			return null;
		}
		header.refresh(reader.getHeader());
		return reader;
	}

	@Override
	public void close() {
		for (Reader r : readers) {
			if (r == null) {
				continue;
			}
			r.close();
		}
	}

}
